package org.linloong.modules.apis.monitor.sync;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linloong.modules.apis.monitor.entity.DeviceGroup;
import org.linloong.modules.apis.monitor.entity.DeviceInfo;
import org.linloong.modules.apis.monitor.mapper.DeviceGroupMapper;
import org.linloong.modules.apis.monitor.mapper.DeviceInfoMapper;
import org.linloong.modules.apis.monitor.service.RealTimeDataService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 设备信息初始化定时任务
 *
 * @author dbo
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InitDeviceInfoTask {

    private final DeviceGroupMapper deviceGroupMapper;
    private final DeviceInfoMapper deviceInfoMapper;
    private final RealTimeDataService realTimeDataService;

    /**
     * 初始化设备信息
     * 使用异步执行避免阻塞应用启动
     */
    @PostConstruct
    @Async
    public void initDeviceInfo() {
        try {
            // 获取指定分组的设备
            List<DeviceGroup> deviceGroups = deviceGroupMapper.selectList(new LambdaQueryWrapper<DeviceGroup>()
                    .in(DeviceGroup::getGroupName, Arrays.asList("生境", "胸径")));
            if (deviceGroups.isEmpty()) {
                return;
            }
            log.info("开始初始化设备信息...");
            // 提取所有设备ID并去重
            Set<String> deviceIds = extractDeviceIds(deviceGroups, deviceInfoMapper);
            log.info("找到 {} 个设备需要初始化", deviceIds.size());
            // 批量处理设备信息
            int successCount = 0;
            for (String deviceId : deviceIds) {
                DeviceInfo deviceInfo = realTimeDataService.getDeviceInfo(deviceId).block();
                if (deviceInfo == null || deviceInfo.getLayout() == null) {
                    log.error("无法获取设备 {} 的信息或layout为空", deviceId);
                }
                successCount += 1;
            }
            log.info("设备信息初始化完成，成功处理 {} 个设备", successCount);

        } catch (Exception e) {
            log.error("设备信息初始化失败", e);
        }
    }

    /**
     * 从设备分组中提取所有设备ID并去重
     */
    private Set<String> extractDeviceIds(List<DeviceGroup> deviceGroups, DeviceInfoMapper deviceInfoMapper) {
        Set<String> ids = deviceGroups.stream()
                .flatMap(group -> Arrays.stream(group.getDeviceIds().split(",")))
                .map(String::trim)
                .filter(deviceId -> !deviceId.isEmpty())
                .collect(Collectors.toSet());
        List<DeviceInfo> deviceInfoList = deviceInfoMapper.selectList(null);
        Set<String> existingIds = deviceInfoList.stream()
                .map(DeviceInfo::getDeviceId)
                .collect(Collectors.toSet());
        ids.removeAll(existingIds);
        return ids;
    }
}
